package com.example.block_chain.utils;

import java.util.ArrayList;
import java.util.List;

/*
 *@description: 获取Merkel树hash值
 *@author: hisen
 *@Time: 2023/11/20  18:10
 */
public class SimpleMerkleTree {
    public static String getTreeNodeHash(List<String> hashList) {
        if (hashList == null || hashList.isEmpty()) return null;
        if (hashList.size() == 1) return getMerKleNodeList(hashList).get(0);
        while (hashList.size() != 1) {
            hashList = getMerKleNodeList(hashList);
        }
        //最后只剩下根节点
        return hashList.get(0);
    }

    private static List<String> getMerKleNodeList(List<String> contentList) {
        List<String> merKleNodeList = new ArrayList<>();
        if (contentList == null || contentList.isEmpty()) return merKleNodeList;
        int index = 0, length = contentList.size();
        while (index < length) {
            String left = contentList.get(index++);
            String right = "";
            if (index < length) right = contentList.get(index++);
            String shawHexValue = SHAUtil.sha256BasedHexTool(left + right);
            merKleNodeList.add(shawHexValue);
        }
        return merKleNodeList;
    }
}
